// mysql -h127.0.0.1 -uroot -p123 -e "select * from edu_iclass_areas" test > /Users/zhengcanrui/WORK/test/test.xls

// Page.Response.Clear();
// Page.Response.Buffer = true;
// Page.Response.ContentEncoding = Encoding.GetEncoding("gb2312");
// Response.Charset = "gb2312";
// Page.Response.AddHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyMMdd_hhmmss") + ".csv");
// Page.Response.ContentEncoding = Encoding.GetEncoding("gb2312");//设置输出流为简体中文
// Page.Response.ContentType = "text/txt";//设置输出文件类型为excel文件。 // application/x-xls
// Page.Response.Write(sb.ToString());
// Page.Response.End();

const fs = require('fs');
const exec = require('child_process').exec;

var createTimestamp = function () {
    return parseInt(new Date().getTime() / 1000) + '';
};

var exportFn = (tableName, dataType, cb) => {
    if (dataType == 'excel') {
        var timestamp = createTimestamp();
        var fileName = '/home/export/' + timestamp + '.xls';
        exec('mysql -h127.0.0.1 -uxxf -pxiexiaofei -e "select * from ' + tableName + '" production > ' + fileName, (error, stdout, stderr) => {
            if (error) {
                console.error(`exec error: ${error}`);
                return cb({ code: 0, data: `exec error: ${error}` });
            } else {
                // fileName
                fs.readFile(fileName, (err, data) => {
                    if (err) throw err;
                    cb({ code: 1, data: data });
                });
            }
        });

    }
}

module.exports = exportFn;